package ca.michaelmaguire.server.mobiledownload.server;

import ca.michaelmaguire.server.mobiledownload.server.entity.AppEvent;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PingServlet extends BaseRecordingServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -808843734175342318L;
	private static final Logger log = Logger.getLogger(PingServlet.class
			.getName());

	private static final String URL_SUFFIX_TO_CHECK_FOR = "ping/";

	/**
	 * Override service so that this method responds to both POST and GET.
	 */
	protected void service(HttpServletRequest aHttpServletRequest,
			HttpServletResponse aHttpServletResponse) throws ServletException,
			IOException {
		try {
			String url = aHttpServletRequest.getRequestURI();

			int indexOfFirstSlash = url.indexOf(URL_SUFFIX_TO_CHECK_FOR)
					+ URL_SUFFIX_TO_CHECK_FOR.length();

			int indexOfSecondSlash = url.indexOf('/', indexOfFirstSlash);

			String userInfoString = url.substring(indexOfFirstSlash,
					indexOfSecondSlash);
			log.warning("userInfoString: " + userInfoString);
			aHttpServletRequest.getSession().setAttribute(
					HeaderConstants.NAME_USER, userInfoString);

			String appString = url.substring(indexOfSecondSlash + 1);
			log.warning("appString: " + appString);

			recordEvent(aHttpServletRequest, appString, AppEvent.USE);

		} catch (Exception aException) {
			throw new ServletException(aException);
		}
	}

}